import { Input, Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import React, { useEffect, useMemo, useState } from 'react';
const { Search } = Input;
const TreeNode = Tree.TreeNode;

const res: DataNode[] = [
  {
    title: '个人工作台',
    key: '0-0',
    children: [
      {
        title: '待办业务',
        key: '0-0-0',
        children: [{ title: '架构部', key: '0-0-0-0' }],
      },
      {
        title: '待办业务',
        key: '0-0-1',
      },
    ],
  },
  {
    title: '合作方应用管理',
    key: '0-1',
    children: [
      { title: '合作方注册管理', key: '0-1-0-0' },
      { title: '合作方管理', key: '0-1-0-1' },
      { title: '合作方变更管理', key: '0-1-0-2' },
      { title: '联系人申请管理', key: '0-1-0-3' },
    ],
  },
  {
    title: '供应商黑名单管理',
    key: '0-2',
    isLeaf: false,
    children: [
      { title: '合作方注册管理', key: '0-1-0-0' },
      { title: '合作方管理', key: '0-1-0-1' },
      { title: '合作方变更管理', key: '0-1-0-2' },
      { title: '联系人申请管理', key: '0-1-0-3' },
    ],
  },
];
const dataList: { key: React.Key; title: any }[] = [];

const searchTree: React.FC = () => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [isLoaded, setIsLoaded] = useState(false);

  const [defaultData, setDefaultData] = useState<DataNode[]>([]);
  useEffect(() => {
    setTimeout(() => {
      setDefaultData(res);
      generateList(res);
      setIsLoaded(true); // 标记数据已加载
    }, 3000); // 模拟请求3秒之后获取数据源
  }, []);

  const generateList = (data: DataNode[]) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title });
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey!;
  };

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, defaultData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const treeData = useMemo(() => {
    if (!isLoaded) return []; //
    console.log(searchValue, 99999);
    const loop = (data: DataNode[]): DataNode[] =>
      data.map((item) => {
        console.log(item, 88888);
        const strTitle = item.title as any;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span
                className="site-tree-search-value"
                style={{ background: 'pink' }}
              >
                {searchValue}
              </span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(defaultData);
  }, [searchValue, isLoaded, defaultData]);

  const onSelectData = (val, info) => {
    console.log('val', val);
    console.log('info', info);
  };

  return (
    <div>
      <Search
        style={{ marginBottom: 8 }}
        placeholder="请输入组织名称"
        onChange={onChange}
      />
      <Tree
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        treeData={treeData}
        showIcon={true}
        onSelect={onSelectData}
      />
    </div>
  );
};

export default searchTree;
